<!DOCTYPE html><html lang="zh"><head><meta charset="utf-8"><meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"><meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1,minimum-scale=1,user-scalable=no,minimal-ui"><meta name="renderer" content="webkit"><meta http-equiv="Cache-Control" content="no-transform"><meta http-equiv="Cache-Control" content="no-siteapp"><meta name="apple-mobile-web-app-capable" content="yes"><meta name="apple-mobile-web-app-status-bar-style" content="black"><meta name="format-detection" content="telephone=no,email=no,adress=no"><meta name="theme-color" content="#000000"><meta http-equiv="window-target" content="_top"><title>FastAPI | 教程 | 请求体-嵌套模型 | 你过来啊！</title><meta name="description" content="https:&#x2F;&#x2F;fastapi.tiangolo.com&#x2F;tutorial&#x2F;body-nested-models&#x2F;  请求体-嵌套模型使用FastAPI，您可以定义，验证，记录和使用任意深度嵌套的模型（这要归功于Pydantic）。 List fields您可以将属性定义为子类型。例如，Python list： 1234567891011121314151617181920from typing"><meta property="og:type" content="article"><meta property="og:title" content="FastAPI | 教程 | 请求体-嵌套模型"><meta property="og:url" content="https://xuqinmin.gitee.io/posts/3208273745.html"><meta property="og:site_name" content="你过来啊！"><meta property="og:description" content="https:&#x2F;&#x2F;fastapi.tiangolo.com&#x2F;tutorial&#x2F;body-nested-models&#x2F;  请求体-嵌套模型使用FastAPI，您可以定义，验证，记录和使用任意深度嵌套的模型（这要归功于Pydantic）。 List fields您可以将属性定义为子类型。例如，Python list： 1234567891011121314151617181920from typing"><meta property="og:locale" content="zh_CN"><meta property="og:image" content="https://xuqinmin.com/images/fastapi/12/image01.png"><meta property="article:published_time" content="2020-09-24T09:51:35.000Z"><meta property="article:modified_time" content="2020-09-24T11:00:48.654Z"><meta property="article:author" content="Xuqm"><meta property="article:tag" content="fastapi"><meta property="article:tag" content="后端"><meta name="twitter:card" content="summary"><meta name="twitter:image" content="https://xuqinmin.com/images/fastapi/12/image01.png"><link rel="canonical" href="https://xuqinmin.gitee.io/posts/3208273745.html"><link rel="alternate" href="/atom.xml" title="你过来啊！" type="application/atom+xml"><link rel="icon" href="/images/favicon.png" type="image/x-icon"><link rel="stylesheet" href="/css/style.css"><link href="//cdn.jsdelivr.net/npm/@fancyapps/fancybox@3.3.5/dist/jquery.fancybox.min.css" rel="stylesheet"><meta name="generator" content="Hexo 5.4.2"></head><body class="main-center" itemscope itemtype="http://schema.org/WebPage"><header class="header" itemscope itemtype="http://schema.org/WPHeader"><div class="slimContent"><div class="navbar-header"><div class="profile-block text-center"><a id="avatar" href="https://xuqinmin.com/xuqinmin12" target="_blank"><img class="img-circle img-rotate" src="/images/avatar.jpg" width="200" height="200"></a><h2 id="name" class="hidden-xs hidden-sm">XUQM</h2><h3 id="title" class="hidden-xs hidden-sm hidden-md">Android开发</h3><small id="location" class="text-muted hidden-xs hidden-sm"><i class="icon icon-map-marker"></i> Beijing, China</small></div><div class="search" id="search-form-wrap"><form class="search-form sidebar-form"><div class="input-group"><input type="text" class="search-form-input form-control" placeholder="搜索"> <span class="input-group-btn"><button type="submit" class="search-form-submit btn btn-flat" onclick="return!1"><i class="icon icon-search"></i></button></span></div></form><div class="ins-search"><div class="ins-search-mask"></div><div class="ins-search-container"><div class="ins-input-wrapper"><input type="text" class="ins-search-input" placeholder="想要查找什么..." x-webkit-speech> <button type="button" class="close ins-close ins-selectable" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button></div><div class="ins-section-wrapper"><div class="ins-section-container"></div></div></div></div></div><button class="navbar-toggle collapsed" type="button" data-toggle="collapse" data-target="#main-navbar" aria-controls="main-navbar" aria-expanded="false"><span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span></button></div><nav id="main-navbar" class="collapse navbar-collapse" itemscope itemtype="http://schema.org/SiteNavigationElement" role="navigation"><ul class="nav navbar-nav main-nav menu-highlight"><li class="menu-item menu-item-home"><a href="/"><i class="icon icon-home-fill"></i> <span class="menu-title">首页</span></a></li><li class="menu-item menu-item-archives"><a href="/archives"><i class="icon icon-archives-fill"></i> <span class="menu-title">归档</span></a></li><li class="menu-item menu-item-categories"><a href="/categories"><i class="icon icon-folder"></i> <span class="menu-title">分类</span></a></li><li class="menu-item menu-item-tags"><a href="/tags"><i class="icon icon-tags"></i> <span class="menu-title">标签</span></a></li><li class="menu-item menu-item-repository"><a href="/repository"><i class="icon icon-project"></i> <span class="menu-title">项目</span></a></li><li class="menu-item menu-item-about"><a href="/about"><i class="icon icon-cup-fill"></i> <span class="menu-title">关于</span></a></li></ul><ul class="social-links"><li><a href="https://github.com/xuqm" target="_blank" title="Github" data-toggle="tooltip" data-placement="top"><i class="icon icon-github"></i></a></li><li><a href="https://gitee.com/xuqinmin" target="_blank" title="Gitee" data-toggle="tooltip" data-placement="top"><i class="icon icon-gitee"></i></a></li><li><a href="/atom.xml" target="_blank" title="Rss" data-toggle="tooltip" data-placement="top"><i class="icon icon-rss"></i></a></li></ul></nav></div></header><aside class="sidebar" itemscope itemtype="http://schema.org/WPSideBar"><div class="slimContent"><div class="widget"><h3 class="widget-title">公告</h3><div class="widget-body"><div id="board"><div class="content"><p>欢迎交流与分享经验!</p></div></div></div></div><div class="widget"><h3 class="widget-title">分类</h3><div class="widget-body"><ul class="category-list"><li class="category-list-item"><a class="category-list-link" href="/categories/Android/">Android</a><span class="category-list-count">3</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/Flutter/">Flutter</a><span class="category-list-count">2</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/python/">python</a><span class="category-list-count">19</span><ul class="category-list-child"><li class="category-list-item"><a class="category-list-link" href="/categories/python/django/">django</a><span class="category-list-count">6</span></li></ul></li><li class="category-list-item"><a class="category-list-link" href="/categories/%E5%89%8D%E7%AB%AF/">前端</a><span class="category-list-count">6</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F/">设计模式</a><span class="category-list-count">10</span></li></ul></div></div><div class="widget"><h3 class="widget-title">标签</h3><div class="widget-body"><ul class="tag-list" itemprop="keywords"><li class="tag-list-item"><a class="tag-list-link" href="/tags/Android/" rel="tag">Android</a><span class="tag-list-count">2</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/Flutter/" rel="tag">Flutter</a><span class="tag-list-count">2</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/React-Native/" rel="tag">React Native</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/android/" rel="tag">android</a><span class="tag-list-count">13</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/css/" rel="tag">css</a><span class="tag-list-count">6</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/django/" rel="tag">django</a><span class="tag-list-count">6</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/fastapi/" rel="tag">fastapi</a><span class="tag-list-count">13</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/ios/" rel="tag">ios</a><span class="tag-list-count">2</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/java/" rel="tag">java</a><span class="tag-list-count">10</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/kotlin/" rel="tag">kotlin</a><span class="tag-list-count">2</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/python/" rel="tag">python</a><span class="tag-list-count">6</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/restframework/" rel="tag">restframework</a><span class="tag-list-count">6</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/%E5%90%8E%E7%AB%AF/" rel="tag">后端</a><span class="tag-list-count">13</span></li></ul></div></div><div class="widget"><h3 class="widget-title">标签云</h3><div class="widget-body tagcloud"><a href="/tags/Android/" style="font-size:13.25px">Android</a> <a href="/tags/Flutter/" style="font-size:13.25px">Flutter</a> <a href="/tags/React-Native/" style="font-size:13px">React Native</a> <a href="/tags/android/" style="font-size:14px">android</a> <a href="/tags/css/" style="font-size:13.5px">css</a> <a href="/tags/django/" style="font-size:13.5px">django</a> <a href="/tags/fastapi/" style="font-size:14px">fastapi</a> <a href="/tags/ios/" style="font-size:13.25px">ios</a> <a href="/tags/java/" style="font-size:13.75px">java</a> <a href="/tags/kotlin/" style="font-size:13.25px">kotlin</a> <a href="/tags/python/" style="font-size:13.5px">python</a> <a href="/tags/restframework/" style="font-size:13.5px">restframework</a> <a href="/tags/%E5%90%8E%E7%AB%AF/" style="font-size:14px">后端</a></div></div><div class="widget"><h3 class="widget-title">归档</h3><div class="widget-body"><ul class="archive-list"><li class="archive-list-item"><a class="archive-list-link" href="/archives/2023/05/">五月 2023</a><span class="archive-list-count">1</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2020/10/">十月 2020</a><span class="archive-list-count">2</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2020/09/">九月 2020</a><span class="archive-list-count">13</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2020/05/">五月 2020</a><span class="archive-list-count">12</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2020/04/">四月 2020</a><span class="archive-list-count">12</span></li></ul></div></div><div class="widget"><h3 class="widget-title">最新文章</h3><div class="widget-body"><ul class="recent-post-list list-unstyled no-thumbnail"><li><div class="item-inner"><p class="item-category"><a class="category-link" href="/categories/Android/">Android</a></p><p class="item-title"><a href="/posts/217975334.html" class="title">Android日常错误记录</a></p><p class="item-date"><time datetime="2023-05-29T05:54:35.000Z" itemprop="datePublished">2023-05-29</time></p></div></li><li><div class="item-inner"><p class="item-category"><a class="category-link" href="/categories/Flutter/">Flutter</a></p><p class="item-title"><a href="/posts/899076041.html" class="title">跨平台方案 |Flutter |Flutter浅尝</a></p><p class="item-date"><time datetime="2020-10-30T08:47:15.000Z" itemprop="datePublished">2020-10-30</time></p></div></li><li><div class="item-inner"><p class="item-category"><a class="category-link" href="/categories/Flutter/">Flutter</a></p><p class="item-title"><a href="/posts/3421344940.html" class="title">跨平台方案 |Flutter |Flutter与RN简单对比</a></p><p class="item-date"><time datetime="2020-10-23T08:57:35.000Z" itemprop="datePublished">2020-10-23</time></p></div></li><li><div class="item-inner"><p class="item-category"><a class="category-link" href="/categories/python/">python</a></p><p class="item-title"><a href="/posts/3925265046.html" class="title">FastAPI | 教程 | 额外的模式</a></p><p class="item-date"><time datetime="2020-09-25T03:15:34.000Z" itemprop="datePublished">2020-09-25</time></p></div></li><li><div class="item-inner"><p class="item-category"><a class="category-link" href="/categories/python/">python</a></p><p class="item-title"><a href="/posts/3208273745.html" class="title">FastAPI | 教程 | 请求体-嵌套模型</a></p><p class="item-date"><time datetime="2020-09-24T09:51:35.000Z" itemprop="datePublished">2020-09-24</time></p></div></li></ul></div></div></div></aside><aside class="sidebar sidebar-toc collapse in" id="collapseToc" itemscope itemtype="http://schema.org/WPSideBar"><div class="slimContent"><nav id="toc" class="article-toc"><h3 class="toc-title">文章目录</h3><ol class="toc"><li class="toc-item toc-level-1"><a class="toc-link" href="#%E8%AF%B7%E6%B1%82%E4%BD%93-%E5%B5%8C%E5%A5%97%E6%A8%A1%E5%9E%8B"><span class="toc-number">1.</span> <span class="toc-text">请求体-嵌套模型</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#List-fields"><span class="toc-number">1.1.</span> <span class="toc-text">List fields</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%85%B7%E6%9C%89%E7%B1%BB%E5%9E%8B%E5%8F%82%E6%95%B0%E7%9A%84List-fields"><span class="toc-number">1.2.</span> <span class="toc-text">具有类型参数的List fields</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E4%BB%8Etyping%E5%AF%BC%E5%85%A5-List"><span class="toc-number">1.2.1.</span> <span class="toc-text">从typing导入 List</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%A3%B0%E6%98%8E%E4%B8%80%E4%B8%AA%E6%9C%89%E7%B1%BB%E5%9E%8B%E5%8F%82%E6%95%B0%E7%9A%84List"><span class="toc-number">1.2.2.</span> <span class="toc-text">声明一个有类型参数的List</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E9%9B%86%E5%90%88%E7%B1%BB%E5%9E%8B"><span class="toc-number">1.3.</span> <span class="toc-text">集合类型</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%B5%8C%E5%A5%97%E6%A8%A1%E5%9E%8B"><span class="toc-number">1.4.</span> <span class="toc-text">嵌套模型</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%AE%9A%E4%B9%89%E4%B8%80%E4%B8%AA%E5%AD%90%E6%A8%A1%E5%9E%8B"><span class="toc-number">1.4.1.</span> <span class="toc-text">定义一个子模型</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E4%BD%BF%E7%94%A8%E5%AD%90%E6%A8%A1%E5%9E%8B%E4%BD%9C%E4%B8%BA%E7%B1%BB%E5%9E%8B"><span class="toc-number">1.4.2.</span> <span class="toc-text">使用子模型作为类型</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E7%89%B9%E6%AE%8A%E7%B1%BB%E5%9E%8B%E5%92%8C%E9%AA%8C%E8%AF%81"><span class="toc-number">1.5.</span> <span class="toc-text">特殊类型和验证</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%B8%A6%E6%9C%89%E5%AD%90%E7%B1%BB%E5%9E%8B%E5%88%97%E8%A1%A8%E7%9A%84%E5%B1%9E%E6%80%A7"><span class="toc-number">1.6.</span> <span class="toc-text">带有子类型列表的属性</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%B7%B1%E5%B1%82%E5%B5%8C%E5%A5%97%E6%A8%A1%E5%9E%8B"><span class="toc-number">1.7.</span> <span class="toc-text">深层嵌套模型</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Bodies-of-pure-lists"><span class="toc-number">1.8.</span> <span class="toc-text">Bodies of pure lists</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%97%A0%E5%A4%84%E4%B8%8D%E5%9C%A8%E7%9A%84%E7%BC%96%E8%BE%91%E5%99%A8%E6%94%AF%E6%8C%81"><span class="toc-number">1.9.</span> <span class="toc-text">无处不在的编辑器支持</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E4%BB%BB%E6%84%8FdictS%E7%9A%84%E5%AE%9E%E4%BD%93"><span class="toc-number">1.10.</span> <span class="toc-text">任意dictS的实体</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%80%BB%E7%BB%93"><span class="toc-number">1.11.</span> <span class="toc-text">总结</span></a></li></ol></li></ol></nav></div></aside><main class="main" role="main"><div class="content"><article id="post-FastApi---12教程-请求体-嵌套模型" class="article article-type-post" itemscope itemtype="http://schema.org/BlogPosting"><div class="article-header"><h1 class="article-title" itemprop="name">FastAPI | 教程 | 请求体-嵌套模型</h1><div class="article-meta"><span class="article-date"><i class="icon icon-calendar-check"></i> <a href="/posts/3208273745.html" class="article-date"><time datetime="2020-09-24T09:51:35.000Z" itemprop="datePublished">2020-09-24</time> </a></span><span class="article-category"><i class="icon icon-folder"></i> <a class="article-category-link" href="/categories/python/">python</a> </span><span class="article-tag"><i class="icon icon-tags"></i> <a class="article-tag-link-link" href="/tags/fastapi/" rel="tag">fastapi</a>, <a class="article-tag-link-link" href="/tags/%E5%90%8E%E7%AB%AF/" rel="tag">后端</a> </span><span class="article-read hidden-xs"><i class="icon icon-eye-fill" aria-hidden="true"></i> <span id="busuanzi_container_page_pv"><span id="busuanzi_value_page_pv">0</span> </span></span><span class="post-comment"><i class="icon icon-comment"></i> <a href="/posts/3208273745.html#comments" class="article-comment-link">评论</a></span> <span class="post-wordcount hidden-xs" itemprop="wordCount">字数统计: 2k(字)</span> <span class="post-readcount hidden-xs" itemprop="timeRequired">阅读时长: 9(分)</span></div></div><div class="article-entry marked-body" itemprop="articleBody"><blockquote><p><a target="_blank" rel="noopener" href="https://fastapi.tiangolo.com/tutorial/body-nested-models/">https://fastapi.tiangolo.com/tutorial/body-nested-models/</a></p></blockquote><h1 id="请求体-嵌套模型"><a href="#请求体-嵌套模型" class="headerlink" title="请求体-嵌套模型"></a>请求体-嵌套模型</h1><p>使用<strong>FastAPI</strong>，您可以定义，验证，记录和使用任意深度嵌套的模型（这要归功于Pydantic）。</p><h2 id="List-fields"><a href="#List-fields" class="headerlink" title="List fields"></a>List fields</h2><p>您可以将属性定义为子类型。例如，Python <code>list</code>：</p><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> typing <span class="keyword">import</span> <span class="type">Optional</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">from</span> fastapi <span class="keyword">import</span> FastAPI</span><br><span class="line"><span class="keyword">from</span> pydantic <span class="keyword">import</span> BaseModel</span><br><span class="line"></span><br><span class="line">app = FastAPI()</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Item</span>(<span class="params">BaseModel</span>):</span></span><br><span class="line">    name: <span class="built_in">str</span></span><br><span class="line">    description: <span class="type">Optional</span>[<span class="built_in">str</span>] = <span class="literal">None</span></span><br><span class="line">    price: <span class="built_in">float</span></span><br><span class="line">    tax: <span class="type">Optional</span>[<span class="built_in">float</span>] = <span class="literal">None</span></span><br><span class="line">    tags: <span class="built_in">list</span> = []</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="meta">@app.put(<span class="params"><span class="string">&quot;/items/&#123;item_id&#125;&quot;</span></span>)</span></span><br><span class="line"><span class="keyword">async</span> <span class="function"><span class="keyword">def</span> <span class="title">update_item</span>(<span class="params">item_id: <span class="built_in">int</span>, item: Item</span>):</span></span><br><span class="line">    results = &#123;<span class="string">&quot;item_id&quot;</span>: item_id, <span class="string">&quot;item&quot;</span>: item&#125;</span><br><span class="line">    <span class="keyword">return</span> results</span><br></pre></td></tr></table></figure><p>在这里，<code>tags</code>被定义为item里面的一个列表。</p><h2 id="具有类型参数的List-fields"><a href="#具有类型参数的List-fields" class="headerlink" title="具有类型参数的List fields"></a>具有类型参数的List fields</h2><p>Python使用一种特定的方式来声明具有内部类型或“类型参数”的列表：</p><h3 id="从typing导入-List"><a href="#从typing导入-List" class="headerlink" title="从typing导入 List"></a>从<code>typing</code>导入 <code>List</code></h3><p>首先，<code>List</code>从标准Python <code>typing</code>模块导入：</p><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> typing <span class="keyword">import</span> <span class="type">List</span>, <span class="type">Optional</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">from</span> fastapi <span class="keyword">import</span> FastAPI</span><br><span class="line"><span class="keyword">from</span> pydantic <span class="keyword">import</span> BaseModel</span><br><span class="line"></span><br><span class="line">app = FastAPI()</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Item</span>(<span class="params">BaseModel</span>):</span></span><br><span class="line">    name: <span class="built_in">str</span></span><br><span class="line">    description: <span class="type">Optional</span>[<span class="built_in">str</span>] = <span class="literal">None</span></span><br><span class="line">    price: <span class="built_in">float</span></span><br><span class="line">    tax: <span class="type">Optional</span>[<span class="built_in">float</span>] = <span class="literal">None</span></span><br><span class="line">    tags: <span class="type">List</span>[<span class="built_in">str</span>] = []<span class="comment">############</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="meta">@app.put(<span class="params"><span class="string">&quot;/items/&#123;item_id&#125;&quot;</span></span>)</span></span><br><span class="line"><span class="keyword">async</span> <span class="function"><span class="keyword">def</span> <span class="title">update_item</span>(<span class="params">item_id: <span class="built_in">int</span>, item: Item</span>):</span></span><br><span class="line">    results = &#123;<span class="string">&quot;item_id&quot;</span>: item_id, <span class="string">&quot;item&quot;</span>: item&#125;</span><br><span class="line">    <span class="keyword">return</span> results</span><br></pre></td></tr></table></figure><h3 id="声明一个有类型参数的List"><a href="#声明一个有类型参数的List" class="headerlink" title="声明一个有类型参数的List"></a>声明一个有类型参数的<code>List</code></h3><p>声明一个有类型参数(子类型)的types，如<code>list</code>，<code>dict</code>，<code>tuple</code>：</p><ul><li>从<code>typing</code>模块导入它们</li><li>使用方括号将内部类型作为“类型参数”传递：<code>[</code> 和 <code>]</code></li></ul><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> typing <span class="keyword">import</span> <span class="type">List</span></span><br><span class="line"></span><br><span class="line">my_list: <span class="type">List</span>[<span class="built_in">str</span>]</span><br></pre></td></tr></table></figure><p>这就是Python下面所有类型声明的标准语法。</p><p>所有具有内部类型的模型属性都使用相同的标准语法。</p><p>因此，在我们的示例中，<code>tags</code>就是一个“字符串列表”：</p><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> typing <span class="keyword">import</span> <span class="type">List</span>, <span class="type">Optional</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">from</span> fastapi <span class="keyword">import</span> FastAPI</span><br><span class="line"><span class="keyword">from</span> pydantic <span class="keyword">import</span> BaseModel</span><br><span class="line"></span><br><span class="line">app = FastAPI()</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Item</span>(<span class="params">BaseModel</span>):</span></span><br><span class="line">    name: <span class="built_in">str</span></span><br><span class="line">    description: <span class="type">Optional</span>[<span class="built_in">str</span>] = <span class="literal">None</span></span><br><span class="line">    price: <span class="built_in">float</span></span><br><span class="line">    tax: <span class="type">Optional</span>[<span class="built_in">float</span>] = <span class="literal">None</span></span><br><span class="line">    tags: <span class="type">List</span>[<span class="built_in">str</span>] = []</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="meta">@app.put(<span class="params"><span class="string">&quot;/items/&#123;item_id&#125;&quot;</span></span>)</span></span><br><span class="line"><span class="keyword">async</span> <span class="function"><span class="keyword">def</span> <span class="title">update_item</span>(<span class="params">item_id: <span class="built_in">int</span>, item: Item</span>):</span></span><br><span class="line">    results = &#123;<span class="string">&quot;item_id&quot;</span>: item_id, <span class="string">&quot;item&quot;</span>: item&#125;</span><br><span class="line">    <span class="keyword">return</span> results</span><br></pre></td></tr></table></figure><h2 id="集合类型"><a href="#集合类型" class="headerlink" title="集合类型"></a>集合类型</h2><p>但是，理论上”<code>tags</code>“不应该重复，它们可能是独一无二的。</p><p>这个时候<code>set</code>出现了，它是<code>Python</code>用于一组唯一项的特殊数据类型。</p><p>然后我们可以导入<code>Set</code>并声明<code>tags</code>为具有<code>str</code>类型的<code>set</code>：</p><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> typing <span class="keyword">import</span> <span class="type">Optional</span>, <span class="type">Set</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">from</span> fastapi <span class="keyword">import</span> FastAPI</span><br><span class="line"><span class="keyword">from</span> pydantic <span class="keyword">import</span> BaseModel</span><br><span class="line"></span><br><span class="line">app = FastAPI()</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Item</span>(<span class="params">BaseModel</span>):</span></span><br><span class="line">    name: <span class="built_in">str</span></span><br><span class="line">    description: <span class="type">Optional</span>[<span class="built_in">str</span>] = <span class="literal">None</span></span><br><span class="line">    price: <span class="built_in">float</span></span><br><span class="line">    tax: <span class="type">Optional</span>[<span class="built_in">float</span>] = <span class="literal">None</span></span><br><span class="line">    tags: <span class="type">Set</span>[<span class="built_in">str</span>] = <span class="built_in">set</span>()</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="meta">@app.put(<span class="params"><span class="string">&quot;/items/&#123;item_id&#125;&quot;</span></span>)</span></span><br><span class="line"><span class="keyword">async</span> <span class="function"><span class="keyword">def</span> <span class="title">update_item</span>(<span class="params">item_id: <span class="built_in">int</span>, item: Item</span>):</span></span><br><span class="line">    results = &#123;<span class="string">&quot;item_id&quot;</span>: item_id, <span class="string">&quot;item&quot;</span>: item&#125;</span><br><span class="line">    <span class="keyword">return</span> results</span><br></pre></td></tr></table></figure><p>这样，即使收到带有重复数据的请求，该请求也将被转换为一组唯一的item。</p><p>即使源重复，每当输出该数据时，它们也将作为一组唯一项输出。</p><p>它也将相应地被注释/记录。</p><h2 id="嵌套模型"><a href="#嵌套模型" class="headerlink" title="嵌套模型"></a>嵌套模型</h2><p>Pydantic model 的每个属性都有一个类型。</p><p>但是该类型本身可以是另一种Pydantic model 。</p><p>因此，您可以使用特定的属性名、类型和验证来声明深度嵌套的JSON“对象”。</p><p>这些都是可以任意嵌套的。</p><h3 id="定义一个子模型"><a href="#定义一个子模型" class="headerlink" title="定义一个子模型"></a>定义一个子模型</h3><p>例如，我们可以定义一个<code>Image</code>模型：</p><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> typing <span class="keyword">import</span> <span class="type">Optional</span>, <span class="type">Set</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">from</span> fastapi <span class="keyword">import</span> FastAPI</span><br><span class="line"><span class="keyword">from</span> pydantic <span class="keyword">import</span> BaseModel</span><br><span class="line"></span><br><span class="line">app = FastAPI()</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Image</span>(<span class="params">BaseModel</span>):</span></span><br><span class="line">    url: <span class="built_in">str</span></span><br><span class="line">    name: <span class="built_in">str</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Item</span>(<span class="params">BaseModel</span>):</span></span><br><span class="line">    name: <span class="built_in">str</span></span><br><span class="line">    description: <span class="type">Optional</span>[<span class="built_in">str</span>] = <span class="literal">None</span></span><br><span class="line">    price: <span class="built_in">float</span></span><br><span class="line">    tax: <span class="type">Optional</span>[<span class="built_in">float</span>] = <span class="literal">None</span></span><br><span class="line">    tags: <span class="type">Set</span>[<span class="built_in">str</span>] = []</span><br><span class="line">    image: <span class="type">Optional</span>[Image] = <span class="literal">None</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="meta">@app.put(<span class="params"><span class="string">&quot;/items/&#123;item_id&#125;&quot;</span></span>)</span></span><br><span class="line"><span class="keyword">async</span> <span class="function"><span class="keyword">def</span> <span class="title">update_item</span>(<span class="params">item_id: <span class="built_in">int</span>, item: Item</span>):</span></span><br><span class="line">    results = &#123;<span class="string">&quot;item_id&quot;</span>: item_id, <span class="string">&quot;item&quot;</span>: item&#125;</span><br><span class="line">    <span class="keyword">return</span> results</span><br></pre></td></tr></table></figure><h3 id="使用子模型作为类型"><a href="#使用子模型作为类型" class="headerlink" title="使用子模型作为类型"></a>使用子模型作为类型</h3><p>然后我们可以将其用作属性的类型：</p><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> typing <span class="keyword">import</span> <span class="type">Optional</span>, <span class="type">Set</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">from</span> fastapi <span class="keyword">import</span> FastAPI</span><br><span class="line"><span class="keyword">from</span> pydantic <span class="keyword">import</span> BaseModel</span><br><span class="line"></span><br><span class="line">app = FastAPI()</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Image</span>(<span class="params">BaseModel</span>):</span></span><br><span class="line">    url: <span class="built_in">str</span></span><br><span class="line">    name: <span class="built_in">str</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Item</span>(<span class="params">BaseModel</span>):</span></span><br><span class="line">    name: <span class="built_in">str</span></span><br><span class="line">    description: <span class="type">Optional</span>[<span class="built_in">str</span>] = <span class="literal">None</span></span><br><span class="line">    price: <span class="built_in">float</span></span><br><span class="line">    tax: <span class="type">Optional</span>[<span class="built_in">float</span>] = <span class="literal">None</span></span><br><span class="line">    tags: <span class="type">Set</span>[<span class="built_in">str</span>] = []</span><br><span class="line">    image: <span class="type">Optional</span>[Image] = <span class="literal">None</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="meta">@app.put(<span class="params"><span class="string">&quot;/items/&#123;item_id&#125;&quot;</span></span>)</span></span><br><span class="line"><span class="keyword">async</span> <span class="function"><span class="keyword">def</span> <span class="title">update_item</span>(<span class="params">item_id: <span class="built_in">int</span>, item: Item</span>):</span></span><br><span class="line">    results = &#123;<span class="string">&quot;item_id&quot;</span>: item_id, <span class="string">&quot;item&quot;</span>: item&#125;</span><br><span class="line">    <span class="keyword">return</span> results</span><br></pre></td></tr></table></figure><p>这意味着<strong>FastAPI</strong>将期望类似于以下内容的请求体：</p><figure class="highlight json"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">&#123;</span><br><span class="line">    <span class="attr">&quot;name&quot;</span>: <span class="string">&quot;Foo&quot;</span>,</span><br><span class="line">    <span class="attr">&quot;description&quot;</span>: <span class="string">&quot;The pretender&quot;</span>,</span><br><span class="line">    <span class="attr">&quot;price&quot;</span>: <span class="number">42.0</span>,</span><br><span class="line">    <span class="attr">&quot;tax&quot;</span>: <span class="number">3.2</span>,</span><br><span class="line">    <span class="attr">&quot;tags&quot;</span>: [<span class="string">&quot;rock&quot;</span>, <span class="string">&quot;metal&quot;</span>, <span class="string">&quot;bar&quot;</span>],</span><br><span class="line">    <span class="attr">&quot;image&quot;</span>: &#123;</span><br><span class="line">        <span class="attr">&quot;url&quot;</span>: <span class="string">&quot;http://example.com/baz.jpg&quot;</span>,</span><br><span class="line">        <span class="attr">&quot;name&quot;</span>: <span class="string">&quot;The Foo live&quot;</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p>所以，仅使用<strong>FastAPI进行</strong>声明即可：</p><ul><li>编辑器支持（completion, etc），哪怕是嵌套模型</li><li>数据转换</li><li>数据验证</li><li>自动文档</li></ul><h2 id="特殊类型和验证"><a href="#特殊类型和验证" class="headerlink" title="特殊类型和验证"></a>特殊类型和验证</h2><p>除了str、int、float等普通的单数类型外，还可以使用从str继承的更复杂的单数类型。</p><p>要查看所有选项，请查看<a target="_blank" rel="noopener" href="https://pydantic-docs.helpmanual.io/usage/types/">Pydantic’s exotic types</a>。您将在下一章中看到一些示例。</p><p>例如，在<code>Image</code>模型中，我们有一个<code>url</code>字段，我们可以将其声明为一个不同的<code>str</code>，Pydantic的<code>HttpUrl</code>：</p><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> typing <span class="keyword">import</span> <span class="type">Optional</span>, <span class="type">Set</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">from</span> fastapi <span class="keyword">import</span> FastAPI</span><br><span class="line"><span class="keyword">from</span> pydantic <span class="keyword">import</span> BaseModel, HttpUrl</span><br><span class="line"></span><br><span class="line">app = FastAPI()</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Image</span>(<span class="params">BaseModel</span>):</span></span><br><span class="line">    url: HttpUrl</span><br><span class="line">    name: <span class="built_in">str</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Item</span>(<span class="params">BaseModel</span>):</span></span><br><span class="line">    name: <span class="built_in">str</span></span><br><span class="line">    description: <span class="type">Optional</span>[<span class="built_in">str</span>] = <span class="literal">None</span></span><br><span class="line">    price: <span class="built_in">float</span></span><br><span class="line">    tax: <span class="type">Optional</span>[<span class="built_in">float</span>] = <span class="literal">None</span></span><br><span class="line">    tags: <span class="type">Set</span>[<span class="built_in">str</span>] = []</span><br><span class="line">    image: <span class="type">Optional</span>[Image] = <span class="literal">None</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="meta">@app.put(<span class="params"><span class="string">&quot;/items/&#123;item_id&#125;&quot;</span></span>)</span></span><br><span class="line"><span class="keyword">async</span> <span class="function"><span class="keyword">def</span> <span class="title">update_item</span>(<span class="params">item_id: <span class="built_in">int</span>, item: Item</span>):</span></span><br><span class="line">    results = &#123;<span class="string">&quot;item_id&quot;</span>: item_id, <span class="string">&quot;item&quot;</span>: item&#125;</span><br><span class="line">    <span class="keyword">return</span> results</span><br></pre></td></tr></table></figure><p>将会检查这个字符串是不是有效的URL，并在JSON Schema / OpenAPI中进行记录。</p><h2 id="带有子类型列表的属性"><a href="#带有子类型列表的属性" class="headerlink" title="带有子类型列表的属性"></a>带有子类型列表的属性</h2><p>您还可以使用Pydantic模型作为<code>list</code>，<code>set</code>等的子类型：</p><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> typing <span class="keyword">import</span> <span class="type">List</span>, <span class="type">Optional</span>, <span class="type">Set</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">from</span> fastapi <span class="keyword">import</span> FastAPI</span><br><span class="line"><span class="keyword">from</span> pydantic <span class="keyword">import</span> BaseModel, HttpUrl</span><br><span class="line"></span><br><span class="line">app = FastAPI()</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Image</span>(<span class="params">BaseModel</span>):</span></span><br><span class="line">    url: HttpUrl</span><br><span class="line">    name: <span class="built_in">str</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Item</span>(<span class="params">BaseModel</span>):</span></span><br><span class="line">    name: <span class="built_in">str</span></span><br><span class="line">    description: <span class="type">Optional</span>[<span class="built_in">str</span>] = <span class="literal">None</span></span><br><span class="line">    price: <span class="built_in">float</span></span><br><span class="line">    tax: <span class="type">Optional</span>[<span class="built_in">float</span>] = <span class="literal">None</span></span><br><span class="line">    tags: <span class="type">Set</span>[<span class="built_in">str</span>] = []</span><br><span class="line">    images: <span class="type">Optional</span>[<span class="type">List</span>[Image]] = <span class="literal">None</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="meta">@app.put(<span class="params"><span class="string">&quot;/items/&#123;item_id&#125;&quot;</span></span>)</span></span><br><span class="line"><span class="keyword">async</span> <span class="function"><span class="keyword">def</span> <span class="title">update_item</span>(<span class="params">item_id: <span class="built_in">int</span>, item: Item</span>):</span></span><br><span class="line">    results = &#123;<span class="string">&quot;item_id&quot;</span>: item_id, <span class="string">&quot;item&quot;</span>: item&#125;</span><br><span class="line">    <span class="keyword">return</span> results</span><br></pre></td></tr></table></figure><p>这将期望（转换，验证，记录等）JSON请求体，例如：</p><figure class="highlight json"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line">&#123;</span><br><span class="line">    <span class="attr">&quot;name&quot;</span>: <span class="string">&quot;Foo&quot;</span>,</span><br><span class="line">    <span class="attr">&quot;description&quot;</span>: <span class="string">&quot;The pretender&quot;</span>,</span><br><span class="line">    <span class="attr">&quot;price&quot;</span>: <span class="number">42.0</span>,</span><br><span class="line">    <span class="attr">&quot;tax&quot;</span>: <span class="number">3.2</span>,</span><br><span class="line">    <span class="attr">&quot;tags&quot;</span>: [</span><br><span class="line">        <span class="string">&quot;rock&quot;</span>,</span><br><span class="line">        <span class="string">&quot;metal&quot;</span>,</span><br><span class="line">        <span class="string">&quot;bar&quot;</span></span><br><span class="line">    ],</span><br><span class="line">    <span class="attr">&quot;images&quot;</span>: [</span><br><span class="line">        &#123;</span><br><span class="line">            <span class="attr">&quot;url&quot;</span>: <span class="string">&quot;http://example.com/baz.jpg&quot;</span>,</span><br><span class="line">            <span class="attr">&quot;name&quot;</span>: <span class="string">&quot;The Foo live&quot;</span></span><br><span class="line">        &#125;,</span><br><span class="line">        &#123;</span><br><span class="line">            <span class="attr">&quot;url&quot;</span>: <span class="string">&quot;http://example.com/dave.jpg&quot;</span>,</span><br><span class="line">            <span class="attr">&quot;name&quot;</span>: <span class="string">&quot;The Baz&quot;</span></span><br><span class="line">        &#125;</span><br><span class="line">    ]</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><blockquote><p>注意，<code>images</code>现在是一个image对象的列表</p></blockquote><h2 id="深层嵌套模型"><a href="#深层嵌套模型" class="headerlink" title="深层嵌套模型"></a>深层嵌套模型</h2><p>您可以定义任意深度嵌套的模型：</p><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> typing <span class="keyword">import</span> <span class="type">List</span>, <span class="type">Optional</span>, <span class="type">Set</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">from</span> fastapi <span class="keyword">import</span> FastAPI</span><br><span class="line"><span class="keyword">from</span> pydantic <span class="keyword">import</span> BaseModel, HttpUrl</span><br><span class="line"></span><br><span class="line">app = FastAPI()</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Image</span>(<span class="params">BaseModel</span>):</span></span><br><span class="line">    url: HttpUrl</span><br><span class="line">    name: <span class="built_in">str</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Item</span>(<span class="params">BaseModel</span>):</span></span><br><span class="line">    name: <span class="built_in">str</span></span><br><span class="line">    description: <span class="type">Optional</span>[<span class="built_in">str</span>] = <span class="literal">None</span></span><br><span class="line">    price: <span class="built_in">float</span></span><br><span class="line">    tax: <span class="type">Optional</span>[<span class="built_in">float</span>] = <span class="literal">None</span></span><br><span class="line">    tags: <span class="type">Set</span>[<span class="built_in">str</span>] = []</span><br><span class="line">    images: <span class="type">Optional</span>[<span class="type">List</span>[Image]] = <span class="literal">None</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Offer</span>(<span class="params">BaseModel</span>):</span></span><br><span class="line">    name: <span class="built_in">str</span></span><br><span class="line">    description: <span class="type">Optional</span>[<span class="built_in">str</span>] = <span class="literal">None</span></span><br><span class="line">    price: <span class="built_in">float</span></span><br><span class="line">    items: <span class="type">List</span>[Item]</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="meta">@app.post(<span class="params"><span class="string">&quot;/offers/&quot;</span></span>)</span></span><br><span class="line"><span class="keyword">async</span> <span class="function"><span class="keyword">def</span> <span class="title">create_offer</span>(<span class="params">offer: Offer</span>):</span></span><br><span class="line">    <span class="keyword">return</span> offer</span><br></pre></td></tr></table></figure><blockquote><p><code>offer</code>有一个<code>item</code>的列表，而<code>item</code>也有一个可以为空的<code>image</code>列表</p></blockquote><h2 id="Bodies-of-pure-lists"><a href="#Bodies-of-pure-lists" class="headerlink" title="Bodies of pure lists"></a>Bodies of pure lists</h2><p>如果您期望JSON请求体的根节点JSON <code>array</code>（Python <code>list</code>），则可以在函数的参数中声明类型，与Pydantic模型相同：</p><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">images: <span class="type">List</span>[Image]</span><br></pre></td></tr></table></figure><p>如：</p><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> typing <span class="keyword">import</span> <span class="type">List</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">from</span> fastapi <span class="keyword">import</span> FastAPI</span><br><span class="line"><span class="keyword">from</span> pydantic <span class="keyword">import</span> BaseModel, HttpUrl</span><br><span class="line"></span><br><span class="line">app = FastAPI()</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Image</span>(<span class="params">BaseModel</span>):</span></span><br><span class="line">    url: HttpUrl</span><br><span class="line">    name: <span class="built_in">str</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="meta">@app.post(<span class="params"><span class="string">&quot;/images/multiple/&quot;</span></span>)</span></span><br><span class="line"><span class="keyword">async</span> <span class="function"><span class="keyword">def</span> <span class="title">create_multiple_images</span>(<span class="params">images: <span class="type">List</span>[Image]</span>):</span></span><br><span class="line">    <span class="keyword">return</span> images</span><br></pre></td></tr></table></figure><h2 id="无处不在的编辑器支持"><a href="#无处不在的编辑器支持" class="headerlink" title="无处不在的编辑器支持"></a>无处不在的编辑器支持</h2><p>你可以在任何地方得到编译器的支持。</p><p>即使是列表中的子类型中：</p><p><img src="https://xuqinmin.com/images/fastapi/12/image01.png" alt="img"></p><p>如果直接使用<code>dict</code>而不是Pydantic模型，则无法获得这种编辑器支持。</p><p>而且，传入的dict会自动转换，输出也会自动转换为JSON。</p><h2 id="任意dictS的实体"><a href="#任意dictS的实体" class="headerlink" title="任意dictS的实体"></a>任意<code>dictS</code>的实体</h2><p>您还可以将一个主体声明为具有某种类型的键和其他类型的值的<code>dict</code>。</p><p>不必事先知道什么是有效的字段/属性名（Pydantic模型就是这样）。</p><p>如果您想接收未定义的<code>keys</code>，这将非常有用。</p><hr><p>当你想要其他类型的keys，例如<code>int</code>的时候。</p><p>我们需要看一下下面这段代码。</p><p>在这种情况下，你可以接受任何key为<code>int</code>，value是<code>float</code>类型的<code>dict</code>：</p><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> typing <span class="keyword">import</span> <span class="type">Dict</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">from</span> fastapi <span class="keyword">import</span> FastAPI</span><br><span class="line"></span><br><span class="line">app = FastAPI()</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="meta">@app.post(<span class="params"><span class="string">&quot;/index-weights/&quot;</span></span>)</span></span><br><span class="line"><span class="keyword">async</span> <span class="function"><span class="keyword">def</span> <span class="title">create_index_weights</span>(<span class="params">weights: <span class="type">Dict</span>[<span class="built_in">int</span>, <span class="built_in">float</span>]</span>):</span></span><br><span class="line">    <span class="keyword">return</span> weights</span><br></pre></td></tr></table></figure><blockquote><p>请记住，JSON仅支持<code>str</code>作为<code>keys</code>。</p><p>但是Pydantic具有自动数据转换功能。</p><p>这意味着，即使API客户机只能将字符串作为<code>keys</code>发送，但是只要这些字符串包含纯整数，Pydantic就可以转换并验证它们。</p><p>但是你接收到的字典，必须包含int类型的key和float类型的value。</p></blockquote><h2 id="总结"><a href="#总结" class="headerlink" title="总结"></a>总结</h2><p>使用<strong>FastAPI，</strong>您将拥有Pydantic模型提供的最大灵活性，同时可以使您的代码简单，简短，美观。</p><p>可以得到这些好处：</p><ul><li>编辑器支持（无处不在！）</li><li>数据转换（又名解析/序列化）</li><li>数据验证</li><li>Schema文档</li><li>自动文档</li></ul></div><div class="article-footer"><blockquote class="mt-2x"><ul class="post-copyright list-unstyled"><li class="post-copyright-link hidden-xs"><strong>本文链接：</strong> <a href="https://xuqinmin.gitee.io/posts/3208273745.html" title="FastAPI | 教程 | 请求体-嵌套模型" target="_blank" rel="external">https://xuqinmin.gitee.io/posts/3208273745.html</a></li><li class="post-copyright-license"><strong>版权声明： </strong>本博客所有文章除特别声明外，均采用 <a href="http://creativecommons.org/licenses/by/4.0/deed.zh" target="_blank" rel="external">CC BY 4.0 CN协议</a> 许可协议。转载请注明出处！</li></ul></blockquote><div class="panel panel-default panel-badger"><div class="panel-body"><figure class="media"><div class="media-left"><a href="https://xuqinmin.com/xuqinmin12" target="_blank" class="img-burn thumb-sm visible-lg"><img src="/images/avatar.jpg" class="img-rounded w-full" alt=""></a></div><div class="media-body"><h3 class="media-heading"><a href="https://xuqinmin.com/xuqinmin12" target="_blank"><span class="text-dark">XUQM</span><small class="ml-1x">Android开发</small></a></h3><div>一个啥也不会的Android开发，励志转型ios开发，后来放弃了。还想搞后台，后台不让！python也不同意！！！</div></div></figure></div></div></div></article><section id="comments"><div id="vcomments"></div></section></div><nav class="bar bar-footer clearfix" data-stick-bottom><div class="bar-inner"><ul class="pager pull-left"><li class="prev"><a href="/posts/3925265046.html" title="FastAPI | 教程 | 额外的模式"><i class="icon icon-angle-left" aria-hidden="true"></i><span>&nbsp;&nbsp;上一篇</span></a></li><li class="next"><a href="/posts/3851480459.html" title="FastAPI | 教程 | 请求体-字段"><span>下一篇&nbsp;&nbsp;</span><i class="icon icon-angle-right" aria-hidden="true"></i></a></li><li class="toggle-toc"><a class="toggle-btn collapsed" data-toggle="collapse" href="#collapseToc" aria-expanded="false" title="文章目录" role="button"><span>[&nbsp;</span><span>文章目录</span> <i class="text-collapsed icon icon-anchor"></i> <i class="text-in icon icon-close"></i> <span>]</span></a></li></ul><div class="bar-right"><div class="share-component" data-sites="weibo,qq,wechat,facebook,twitter" data-mobile-sites="weibo,qq,wechat"></div></div></div></nav></main><footer class="footer" itemscope itemtype="http://schema.org/WPFooter"><div style="width:300px;margin:0 auto"><a target="_blank" href="http://www.beian.gov.cn/portal/registerSystemInfo?recordcode=37132902372892" style="display:inline-block;text-decoration:none"><img src="https://www.beian.gov.cn/img/new/gongan.png" style="float:left"><p style="float:left;margin:0 0 0 5px;color:#939393">鲁公网安备 37132902372892号</p></a></div><div style="width:300px;margin:0 auto"><a target="_blank" href="https://beian.miit.gov.cn/" style="display:inline-block;text-decoration:none"><p style="float:left;margin:0 0 0 5px;color:#939393">&nbsp;&nbsp;&nbsp;&nbsp; 鲁ICP备20018775号-3</p></a></div><div>&nbsp;</div><div>&nbsp;</div><ul class="social-links"><li><a href="https://github.com/xuqm" target="_blank" title="Github" data-toggle="tooltip" data-placement="top"><i class="icon icon-github"></i></a></li><li><a href="https://gitee.com/xuqinmin" target="_blank" title="Gitee" data-toggle="tooltip" data-placement="top"><i class="icon icon-gitee"></i></a></li><li><a href="/atom.xml" target="_blank" title="Rss" data-toggle="tooltip" data-placement="top"><i class="icon icon-rss"></i></a></li></ul><div class="copyright">&copy; 2023 Xuqm<div class="publishby">Theme by <a href="https://github.com/cofess" target="_blank">cofess </a>base on <a href="https://github.com/cofess/hexo-theme-pure" target="_blank">pure</a>.</div></div></footer><script src="//cdn.jsdelivr.net/npm/jquery@1.12.4/dist/jquery.min.js"></script><script>window.jQuery||document.write('<script src="js/jquery.min.js"><\/script>')</script><script src="/js/plugin.min.js"></script><script src="/js/application.js"></script><script>window.INSIGHT_CONFIG={TRANSLATION:{POSTS:"文章",PAGES:"页面",CATEGORIES:"分类",TAGS:"标签",UNTITLED:"(未命名)"},ROOT_URL:"/",CONTENT_URL:"/content.json"}</script><script src="/js/insight.js"></script><script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script><script src="//cdn1.lncld.net/static/js/3.0.4/av-min.js"></script><script src="//cdn.jsdelivr.net/npm/valine"></script><script type="text/javascript">var GUEST=["nick","mail","link"],meta=(meta="nick,mail,link").split(",").filter(function(e){return-1<GUEST.indexOf(e)});new Valine({el:"#vcomments",verify:!1,notify:!1,appId:"mRlIqh4MAdByI85z02yNYA2w-gzGzoHsz",appKey:"3LKdn7pI9XqvCqgBhFdLoWgw",placeholder:"来都来了，玩玩呗~~~",avatar:"mm",meta:meta,pageSize:"10",visitor:!1})</script><script src="//cdn.jsdelivr.net/npm/@fancyapps/fancybox@3.3.5/dist/jquery.fancybox.min.js"></script><script>$(document).ready(function(){$("article img").not("[hidden]").not(".panel-body img").each(function(){var a,t,n=$(this),e=n.attr("alt"),r=n.parent("a");r.length<1&&(-1!=(t=(a=this.getAttribute("src")).lastIndexOf("?"))&&(a=a.substring(0,t)),r=n.wrap('<a href="'+a+'"></a>').parent("a")),r.attr("data-fancybox","images"),e&&r.attr("data-caption",e)}),$().fancybox({selector:'[data-fancybox="images"]',hash:!1,loop:!1})})</script></body></html>